package org.orz.story.pms.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.orz.cloud.auth.AuthErrorEnum;
import org.orz.cloud.auth.UserUtil;
import org.orz.cloud.auth.domain.UserInfo;
import org.orz.cloud.common.exception.BusinessException;
import org.orz.story.pms.api.model.dto.DoAuthDto;
import org.orz.story.pms.biz.enums.ShowFlagEnum;
import org.orz.story.pms.biz.model.dto.PermissionRoleRelationDTO;
import org.orz.story.pms.biz.model.req.*;
import org.orz.story.pms.biz.model.resp.ListMenuInfoResp;
import org.orz.story.pms.biz.model.resp.MenuListResp;
import org.orz.story.pms.biz.persistence.entities.*;
import org.orz.story.pms.biz.persistence.mappers.*;
import org.orz.story.pms.biz.service.PmsPermissionService;
import org.orz.story.pms.common.exception.PmsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static org.orz.cloud.common.enums.AliveFlagEnum.ALIVE;
import static org.orz.cloud.common.enums.AliveFlagEnum.DELETED;

@Service
@Slf4j
public class PmsPermissionServiceImpl implements PmsPermissionService {
    @Autowired
    private PmsWhiteListMapper pmsWhiteListMapper;
    @Autowired
    private PmsAccountRoleMapper pmsAccountRoleMapper;
    @Autowired
    private PmsRolePermissionMapper pmsRolePermissionMapper;
    @Autowired
    private PmsPermissionMapper pmsPermissionMapper;
    @Autowired
    private PmsApiMapper pmsApiMapper;
    @Autowired
    private PmsRoleMapper pmsRoleMapper;
    @Autowired
    private PmsPermissionApiMapper pmsPermissionApiMapper;
    @Autowired
    private PmsRoleApiMapper pmsRoleApiMapper;
    @Autowired
    private PmsAccountMapper pmsAccountMapper;

    @Override
    public void doAuth(DoAuthDto dto) {
        //1.判断接口是否在白名单内
        if(existInWhiteList(dto.getUrl())){
            return;
        }

        //2.用户身份认证
        UserInfo userInfo = doAuthentication(dto.getWorkbench(), dto.getToken());

        //3.用户权限认证
        List<PmsApi> apis = pmsApiMapper.listApiInfoByAccount(userInfo.getAccountId(), dto.getWorkbench(), dto.getUrl());
        if(CollUtil.isEmpty(apis)){
            throw new PmsException(PmsException.Type.PMS_0002);
        }
    }

    /**
     * 查询菜单列表
     */
    @Override
    public List<MenuListResp> getAdminMenuList() {
        UserInfo userInfo = UserUtil.getUserInfo();

        PmsAccount pmsAccount = pmsAccountMapper.selectOne(new LambdaQueryWrapper<PmsAccount>()
                .eq(PmsAccount::getMemAccountId, userInfo.getAccountId())
                .eq(PmsAccount::getAliveFlag, ALIVE.getKey()));
        if(pmsAccount == null){
            throw new PmsException(PmsException.Type.PMS_0004);
        }

        List<PmsPermission> accountPermissions = getAccountPermissions(pmsAccount.getId());
        //递归封装菜单列表的数据
        return packageMenuList(accountPermissions, null, Boolean.TRUE);
    }

    @Override
    public List<MenuListResp> listMenuInfoOfTree(ListMenuInfoOfTreeReq req) {
        List<PmsPermission> permissions = pmsPermissionMapper.selectList(new LambdaQueryWrapper<PmsPermission>()
                .eq(PmsPermission::getAliveFlag, ALIVE.getKey()));
        return packageMenuList(permissions, null, Boolean.FALSE);
    }

    @Override
    public List<ListMenuInfoResp> listMenuInfo(ListMenuInfoReq req) {
        PmsRole role = pmsRoleMapper.selectOne(new LambdaQueryWrapper<PmsRole>()
                .eq(PmsRole::getId, req.getRoleId())
                .eq(PmsRole::getAliveFlag, ALIVE.getKey()));
        if(role == null){
            return Collections.emptyList();
        }

        List<PmsRolePermission> rolePermissions = pmsRolePermissionMapper.selectList(new LambdaQueryWrapper<PmsRolePermission>()
                .eq(PmsRolePermission::getRoleId, req.getRoleId())
                .eq(PmsRolePermission::getAliveFlag, ALIVE.getKey()));
        if(CollUtil.isEmpty(rolePermissions)){
            return Collections.emptyList();
        }

        Set<Long> permissionSet = rolePermissions.stream().map(PmsRolePermission::getPermissionId).collect(Collectors.toSet());
        List<PmsPermission> permissions = pmsPermissionMapper.selectList(new LambdaQueryWrapper<PmsPermission>()
                .in(PmsPermission::getId, permissionSet)
                .eq(PmsPermission::getAliveFlag, ALIVE.getKey()));
        return permissions.stream().map(item -> BeanUtil.toBean(item, ListMenuInfoResp.class)).collect(Collectors.toList());
    }

    @Override
    public void addPermission(AddPermissionReq req) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();

        Long parentId = 0L;
        String parentPermissionCode = "";
        if(req.getParentId() != null && req.getParentId() != 0L){
            PmsPermission parentPermission = pmsPermissionMapper.selectOne(new LambdaQueryWrapper<PmsPermission>()
                    .eq(PmsPermission::getId, req.getParentId())
                    .eq(PmsPermission::getAliveFlag, ALIVE.getKey()));
            if(parentPermission == null){
                throw new PmsException(PmsException.Type.PMS_0008);
            }
            parentId = parentPermission.getId();
            parentPermissionCode = parentPermission.getPermissionCode();
        }

        // 根据父节点的编号查询当前父节点的最后一个子节点
        PmsPermission lastPermission = pmsPermissionMapper.selectOne(new LambdaQueryWrapper<PmsPermission>()
                .eq(PmsPermission::getParentId, parentId)
                .eq(PmsPermission::getAliveFlag, ALIVE.getKey())
                .orderByDesc(PmsPermission::getPermissionCode)
                .last(" limit 1"));
        String permissionCode;
        if(lastPermission == null){
            permissionCode = parentPermissionCode + "0001";
        } else {
            String lastPermissionCode = lastPermission.getPermissionCode();
            String currentLevelIndexStr = lastPermissionCode.substring(lastPermissionCode.length() - 4);
            BigDecimal currentIndex = new BigDecimal(currentLevelIndexStr);
            StringBuilder newPermissionIndex = new StringBuilder(currentIndex.add(BigDecimal.ONE).toString());
            // 前面补0
            for (int i = 0; i < 4 - newPermissionIndex.length(); i++) {
                newPermissionIndex.insert(0, "0");
            }
            permissionCode = parentPermissionCode + newPermissionIndex;
        }

        // 保存权限信息
        PmsPermission insertParam = new PmsPermission();
        insertParam.setPermissionCode(permissionCode);
        insertParam.setParentId(parentId);
        insertParam.setParentPermissionCode(parentPermissionCode);
        insertParam.setName(req.getName());
        insertParam.setUrl(req.getUrl());
        insertParam.setType(req.getType());
        insertParam.setStatus(req.getStatus());
        insertParam.setShowFlag(req.getShowFlag());
        insertParam.setIcon(req.getIcon());
        insertParam.setOrderNum(lastPermission == null ? 1 : lastPermission.getOrderNum() + 1);
        insertParam.setCreateUser(userInfo.getAccountId());
        insertParam.setCreateDate(new Date());
        pmsPermissionMapper.insert(insertParam);
    }

    @Override
    public void updatePermission(UpdatePermissionReq req) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();
        PmsPermission permission = new PmsPermission();
        permission.setId(req.getId());
        permission.setName(req.getName());
        permission.setUrl(req.getUrl());
        permission.setStatus(req.getStatus());
        permission.setShowFlag(req.getShowFlag());
        permission.setIcon(req.getIcon());
        permission.setUpdateUser(userInfo.getAccountId());
        permission.setUpdateDate(new Date());
        pmsPermissionMapper.updateById(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePermission(DeletePermissionReq req) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();

        PmsPermission currentPermission = pmsPermissionMapper.selectOne(new LambdaQueryWrapper<PmsPermission>()
                .eq(PmsPermission::getId, req.getPermissionId())
                .eq(PmsPermission::getAliveFlag, ALIVE.getKey()));
        if(currentPermission == null){
            throw new PmsException(PmsException.Type.PMS_0009);
        }

        // 校验是否有子节点
        Integer subPermissionCount = pmsPermissionMapper.selectCount(new LambdaQueryWrapper<PmsPermission>()
                .eq(PmsPermission::getParentId, currentPermission.getId())
                .eq(PmsPermission::getAliveFlag, ALIVE.getKey()));
        if(subPermissionCount > 0){
            throw new PmsException(PmsException.Type.PMS_0010);
        }


        //删除权限
        PmsPermission permissionDeleteParam = new PmsPermission();
        permissionDeleteParam.setAliveFlag(DELETED.getKey());
        permissionDeleteParam.setUpdateUser(userInfo.getAccountId());
        permissionDeleteParam.setUpdateDate(new Date());
        pmsPermissionMapper.updateById(permissionDeleteParam);

        PmsPermissionApi permissionApi = new PmsPermissionApi();
        permissionApi.setAliveFlag(DELETED.getKey());
        permissionApi.setUpdateUser(userInfo.getAccountId());
        permissionApi.setUpdateDate(new Date());
        pmsPermissionApiMapper.update(permissionApi, new LambdaQueryWrapper<PmsPermissionApi>()
                .eq(PmsPermissionApi::getPermissionId, req.getPermissionId())
                .eq(PmsPermissionApi::getAliveFlag, ALIVE.getKey()));

        List<PmsRolePermission> rolePermissions = pmsRolePermissionMapper.selectList(new LambdaQueryWrapper<PmsRolePermission>()
                .eq(PmsRolePermission::getPermissionId, req.getPermissionId())
                .eq(PmsRolePermission::getAliveFlag, ALIVE.getKey()));

        PmsRolePermission rolePermission = new PmsRolePermission();
        rolePermission.setAliveFlag(DELETED.getKey());
        rolePermission.setUpdateUser(userInfo.getAccountId());
        rolePermission.setUpdateDate(new Date());
        pmsRolePermissionMapper.update(rolePermission, new LambdaQueryWrapper<PmsRolePermission>()
                .eq(PmsRolePermission::getPermissionId, req.getPermissionId())
                .eq(PmsRolePermission::getAliveFlag, ALIVE.getKey()));

        if(CollUtil.isNotEmpty(rolePermissions)){
            Set<Long> roleIds = rolePermissions.stream().map(PmsRolePermission::getRoleId).collect(Collectors.toSet());
            syncPermissionApiInfoToRoleApi(roleIds, Collections.emptySet());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void grantPermission(GrantPermissionReq req) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();
        // 1.重新赋予新的菜单权限
        // 删除原有的菜单的权限
        Date now = new Date();
        PmsRolePermission deletePermissionParam = new PmsRolePermission();
        deletePermissionParam.setAliveFlag(DELETED.getKey());
        deletePermissionParam.setUpdateUser(userInfo.getAccountId());
        deletePermissionParam.setUpdateDate(now);
        pmsRolePermissionMapper.update(deletePermissionParam, new LambdaQueryWrapper<PmsRolePermission>()
                    .eq(PmsRolePermission::getRoleId, req.getRoleId())
                    .eq(PmsRolePermission::getAliveFlag, ALIVE.getKey()));
        // 新增新的菜单权限
        req.getPermissionIds().stream().distinct().forEach(item -> {
            PmsRolePermission insertPermissionParam = new PmsRolePermission();
            insertPermissionParam.setRoleId(req.getRoleId());
            insertPermissionParam.setPermissionId(item);
            insertPermissionParam.setCreateUser(userInfo.getAccountId());
            insertPermissionParam.setCreateDate(now);
            pmsRolePermissionMapper.insert(insertPermissionParam);
        });

        // 2.根据新的菜单权限查询接口权限，并更新到角色权限表里面
        // 删除原有的权限
        PmsRoleApi deleteRoleApiParam = new PmsRoleApi();
        deleteRoleApiParam.setAliveFlag(DELETED.getKey());
        deletePermissionParam.setUpdateUser(userInfo.getAccountId());
        deletePermissionParam.setUpdateDate(now);
        pmsRoleApiMapper.update(deleteRoleApiParam, new LambdaQueryWrapper<PmsRoleApi>()
                    .eq(PmsRoleApi::getRoleId, req.getRoleId())
                    .eq(PmsRoleApi::getAliveFlag, ALIVE.getKey()));

        if(CollUtil.isEmpty(req.getPermissionIds())){
            return;
        }
        // 保存新的权限
        List<PmsPermissionApi> pmsPermissionApis = pmsPermissionApiMapper.selectList(new LambdaQueryWrapper<PmsPermissionApi>()
                .in(PmsPermissionApi::getPermissionId, req.getPermissionIds())
                .eq(PmsPermissionApi::getAliveFlag, ALIVE.getKey()));
        Set<Long> newApiIds = pmsPermissionApis.stream().map(PmsPermissionApi::getApiId).collect(Collectors.toSet());
        newApiIds.forEach(item -> {
            PmsRoleApi insertRoleApiParam = new PmsRoleApi();
            insertRoleApiParam.setRoleId(req.getRoleId());
            insertRoleApiParam.setApiId(item);
            insertRoleApiParam.setCreateUser(userInfo.getAccountId());
            insertRoleApiParam.setCreateDate(now);
            pmsRoleApiMapper.insert(insertRoleApiParam);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addPermissionApi(GrantPermissionApiReq req) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();
        // 1.权限新增接口
        Date now = new Date();
        req.getApiIds().forEach(item -> {
            PmsPermissionApi insertPermissionApiParam = new PmsPermissionApi();
            insertPermissionApiParam.setPermissionId(req.getPermissionId());
            insertPermissionApiParam.setApiId(item);
            insertPermissionApiParam.setCreateUser(userInfo.getAccountId());
            insertPermissionApiParam.setCreateDate(now);
            pmsPermissionApiMapper.insert(insertPermissionApiParam);
        });

        // 2.将新增的信息同步到和权限相关的角色中
        syncPermissionApiInfoToRoleApi(req.getPermissionId(), req.getApiIds());
    }

    @Override
    public void deletePermissionApi(DeletePermissionApiReq req) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();
        // 1.删除权限接口关系
        PmsPermissionApi deleteParam = new PmsPermissionApi();
        deleteParam.setAliveFlag(DELETED.getKey());
        deleteParam.setUpdateUser(userInfo.getAccountId());
        deleteParam.setUpdateDate(new Date());
        pmsPermissionApiMapper.update(deleteParam, new LambdaQueryWrapper<PmsPermissionApi>()
                .eq(PmsPermissionApi::getPermissionId, req.getPermissionId())
                .in(PmsPermissionApi::getApiId, req.getApiIds())
                .eq(PmsPermissionApi::getAliveFlag, ALIVE.getKey()));

        // 2.将删除的信息同步到权限相关的角色中
        syncPermissionApiInfoToRoleApi(req.getPermissionId(), req.getApiIds());
    }

    /**
     * 判断接口是否在白名单中
     * @param url 接口url
     */
    private boolean existInWhiteList(String url) {
        //1.判断接口是否在白名单中，如果在，就不做校验
        List<PmsWhiteList> whiteList = pmsWhiteListMapper.selectList(new LambdaQueryWrapper<PmsWhiteList>()
                .eq(PmsWhiteList::getUrl, url)
                .eq(PmsWhiteList::getAliveFlag, ALIVE.getKey()));
        if(CollUtil.isNotEmpty(whiteList)){
            log.info("url {} is in whiteList.", url);
            return true;
        }
        return false;
    }


    /**
     * 用户身份认证
     */
    private UserInfo doAuthentication(String workbench, String token) {
        log.info("start do authentication.");
        //1.判断userInfo是否为空
        UserInfo userInfo = UserUtil.getUserInfoByToken(token);
        if(userInfo == null){
            log.info("userInfo is null");
            throw new BusinessException(AuthErrorEnum.NOT_LOGIN);
        } else if(userInfo.getAccountId() == null){
            log.info("userInfo is not null, but accountId is null");
            throw new BusinessException(AuthErrorEnum.NOT_LOGIN);
        }

        //2.判断当前用户是否是当前平台的
        List<String> currentWorkbench = userInfo.getWorkBenchList().stream().filter(item -> item.equals(workbench)).collect(Collectors.toList());
        if(CollUtil.isEmpty(currentWorkbench)){
            log.info("user {} is not belongs to workbench {}.", userInfo.getAccountId(), workbench);
            throw new BusinessException(AuthErrorEnum.NOT_LOGIN);
        }
        return userInfo;
    }

    /**
     * 查询账号相关的权限信息
     * @param accountId 账号id
     * @return 权限集合
     */
    private List<PmsPermission> getAccountPermissions(Long accountId){
        //多个权限角色可以权限覆盖
        //查询用户的权限
        //查询用户对应的角色
        List<PmsAccountRole> accountRoles = pmsAccountRoleMapper.selectList(new LambdaQueryWrapper<PmsAccountRole>()
                .eq(PmsAccountRole::getAccountId, accountId)
                .eq(PmsAccountRole::getAliveFlag, ALIVE.getKey()));
        if(CollUtil.isEmpty(accountRoles)){
            return Collections.emptyList();
        }

        Set<Long> roleIdSet = accountRoles.stream().map(PmsAccountRole::getRoleId).collect(Collectors.toSet());

        //查询角色对应的权限
        List<PmsRolePermission> rolePermissions = pmsRolePermissionMapper.selectList(new LambdaQueryWrapper<PmsRolePermission>()
                .in(PmsRolePermission::getRoleId, roleIdSet)
                .eq(PmsRolePermission::getAliveFlag, ALIVE.getKey()));

        if(CollUtil.isEmpty(rolePermissions)){
            return Collections.emptyList();
        }

        //查询权限列表
        Set<Long> permissionIds = rolePermissions.stream().map(PmsRolePermission::getPermissionId).collect(Collectors.toSet());

        return pmsPermissionMapper.selectList(new LambdaQueryWrapper<PmsPermission>()
                .in(PmsPermission::getId, permissionIds)
                .eq(PmsPermission::getAliveFlag, ALIVE.getKey()));
    }

    /**
     * 将菜单封装成树形结构
     * @param originData 原始数据
     * @param parentMenu 父菜单
     */
    private List<MenuListResp> packageMenuList(List<PmsPermission> originData, PmsPermission parentMenu, Boolean filterHideMenu){
        if(CollUtil.isEmpty(originData)){
            return Collections.emptyList();
        }

        Long parentId = parentMenu == null ? 0 : parentMenu.getId();

        List<MenuListResp> resultList = new ArrayList<>();
        for (PmsPermission item : originData) {
            //不是当前菜单的子菜单，或者不展示，就直接跳过
            if(!item.getParentId().equals(parentId)
                    || (item.getShowFlag().equals(ShowFlagEnum.HIDE.getKey()) && filterHideMenu)){
                continue;
            }
            MenuListResp menuListResp = new MenuListResp();
            BeanUtil.copyProperties(item, menuListResp);
            menuListResp.setChildren(packageMenuList(originData, item, filterHideMenu));
            resultList.add(menuListResp);
        }
        return resultList;
    }

    /**
     * 同步权限接口变更信息到角色接口表中
     * @param permissionId 信息变更的权限id
     */
    private void syncPermissionApiInfoToRoleApi(Long permissionId, Set<Long> newApiIds) {
        List<PmsRole> roles = pmsRoleMapper.listAllByPermissionId(permissionId);
        if(CollUtil.isEmpty(roles)){
            return;
        }
        Set<Long> roleIds = roles.stream().map(PmsRole::getId).collect(Collectors.toSet());
        syncPermissionApiInfoToRoleApi(roleIds, newApiIds);
    }

    private void syncPermissionApiInfoToRoleApi(Set<Long> roleIds, Set<Long> newApiIds) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();
        List<PermissionRoleRelationDTO> relations = pmsPermissionApiMapper.listApiRoleInfoByRoleIds(roleIds);
        Map<Long, List<PermissionRoleRelationDTO>> relationMap = relations.stream().collect(Collectors.groupingBy(PermissionRoleRelationDTO::getRoleId));
        if(!relationMap.isEmpty()){
            // 先删除原有的关系
            PmsRoleApi deleteParam = new PmsRoleApi();
            deleteParam.setAliveFlag(DELETED.getKey());
            deleteParam.setUpdateUser(userInfo.getAccountId());
            deleteParam.setUpdateDate(new Date());
            pmsRoleApiMapper.update(deleteParam, new LambdaQueryWrapper<PmsRoleApi>()
                    .in(PmsRoleApi::getRoleId, relationMap.keySet())
                    .eq(PmsRoleApi::getAliveFlag, ALIVE.getKey()));
        }

        // 再新增新的关系
        relationMap.forEach((key,value) -> {
            Set<Long> oldApiIds = value.stream().map(PermissionRoleRelationDTO::getApiId).collect(Collectors.toSet());
            oldApiIds.addAll(newApiIds);
            for (Long item : oldApiIds) {
                PmsRoleApi roleApiInsertParam = new PmsRoleApi();
                roleApiInsertParam.setRoleId(key);
                roleApiInsertParam.setApiId(item);
                roleApiInsertParam.setCreateUser(userInfo.getAccountId());
                roleApiInsertParam.setCreateDate(new Date());
                pmsRoleApiMapper.insert(roleApiInsertParam);
            }
        });
    }

}
